<template>
  <div class="comment-section">
    <div class="comment-header">
      <span v-if="props.commentTotal" class="total-value">
        评论 <span style="font-size: 1rem">{{ props.commentTotal }}</span>
      </span>
      <div v-if="props.commentTotal">
        <span
          :class="[orderBy == 'hot' ? 'active-hot-new' : '']"
          @click="changeOrder('hot')"
          >最热</span
        >
        <span>|</span>
        <span
          :class="[orderBy == 'new' ? 'active-hot-new' : '']"
          @click="changeOrder('new')"
          >最新</span
        >
      </div>
    </div>
    <div class="input-comment">
      <el-avatar :size="32" :src="userAvatar">登录</el-avatar>
      <div>
        <CommentInput
          :parent="true"
          v-model:input-text="inputText"
          @update:inputText="updateInputText"
          @publish="publishComment"
        ></CommentInput>
      </div>
    </div>

    <!-- 循环显示每条评论 -->
    <div v-for="comment in comments" :key="comment.id" class="comment-card">
      <div class="comment-left">
        <!-- 用户头像和名称 -->
        <el-avatar :size="32" :src="comment.avatar">游客</el-avatar>
      </div>
      <!-- 评论内容 -->
      <div class="comment-right">
        <div class="comment-body">
          <span class="comment-username">{{ comment.username }}</span>
          <p v-html="comment.content"></p>
          <el-image
            v-if="comment.commentPic"
            style="width: 190px; height: 135px"
            :src="comment.commentPic"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[comment.commentPic]"
            :initial-index="0"
            fit="cover"
          />
        </div>
        <!-- 底部点赞、踩、回复按钮 -->
        <div class="comment-footer">
          <span>{{ comment.createDate }}</span>
          <span @click="like(comment)">
            <svg
              t="1728311247743"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="5363"
              width="16"
              height="16"
            >
              <path
                d="M939.358251 423.424662c-23.01825-37.252439-62.924121-60.779272-107.019409-63.209624-2.755764-0.38681-5.510504-0.579191-8.347109-0.579191l-152.202471-0.121773c6.649444-28.975938 10.015098-58.653865 10.015098-88.657202 0-28.223808-3.213181-57.139372-9.556657-85.952604-0.447185-2.043542-1.098008-4.006244-1.932002-5.866614-15.820314-57.302077-67.37755-96.841605-127.282918-96.841605-72.827679 0-132.081201 59.254545-132.081201 132.081201 0 3.334955 0.132006 6.66991 0.406253 10.015098-2.196015 57.211003-32.108279 109.947088-80.269162 141.363611-14.447037 9.42465-18.524912 28.773324-9.099239 43.220361 9.414417 14.437827 28.752858 18.535145 43.220361 9.099239 65.811892-42.925648 106.429984-115.325585 108.656699-193.684234 0.030699-1.332345-0.010233-2.663666-0.14224-3.996011-0.203638-2.012843-0.304945-4.016477-0.304945-6.019087 0-38.381146 31.233352-69.614497 69.614497-69.614497 32.57593 0 60.474326 22.204721 67.824735 53.997821 0.356111 1.534959 0.823761 3.019777 1.402953 4.453429 4.696975 22.814612 7.076162 45.579081 7.076162 67.743894 0 37.485753-6.222725 74.352405-18.494213 109.592001-3.324722 9.546424-1.819438 20.111037 4.02671 28.345582 5.856381 8.245801 15.332197 13.146415 25.448602 13.156648l193.226816 0.101307c1.423419 0.264013 2.857071 0.426719 4.300956 0.477884 24.116257 0.9967 45.935192 13.614066 58.603723 34.090423 7.838525 12.31242 11.438517 26.800389 10.431583 41.939181-0.080841 0.945535-0.121773 1.911536-0.11154 2.877537 0 0.854461 0.040932 1.697665 0.11154 2.53166 0.010233 0.335644-0.030699 0.661056-0.11154 0.976234-0.101307 0.376577-0.193405 0.772596-0.284479 1.159406l-74.972529 330.391802c-0.914836 1.281179-1.738597 2.6432-2.449795 4.046153-5.937223 11.762905-14.660908 21.48329-25.346271 28.172643-10.746762 6.812149-23.059182 10.614755-35.757388 11.06194-0.854461-0.061398-513.766226-0.224104-513.766226-0.224104-0.467651-0.020466-0.935302-0.030699-1.402953-0.030699 0 0-111.01542 0.172939-112.718201 0.457418-1.932002 0-3.446495-1.50426-3.446495-3.415796l0.299829-416.334173c0-1.901303 1.545192-3.446495 3.01466-3.456728l1.245364 0.121773c1.174756 0.132006 2.653433 0.284479 3.52836 0.193405l83.82822-0.222057 0 339.367221c0 17.253966 13.979386 31.233352 31.233352 31.233352s31.233352-13.979386 31.233352-31.233352L281.009092 435.350273c0-1.778506 0-8.631588 0-10.411117 0-17.253966-13.979386-30.928407-31.233352-30.928407-1.50426 0-117.547183 0.304945-119.402437 0.304945-36.34272 0-65.913199 29.566386-65.913199 65.893756l-0.299829 416.334173c0 36.337603 29.571503 65.902966 65.913199 65.902966 2.541893 0 111.406323-0.457418 111.406323-0.457418 0.457418 0.020466 0.925069 0.030699 1.382487 0.030699 0 0 511.458671 0.274246 512.505513 0.274246 25.469068 0 50.296523-7.197936 71.647807-20.73116 19.612687-12.281721 35.777855-29.881564 46.839795-50.967812 3.660366-5.622044 6.435573-11.875468 8.256034-18.615986 0.11154-0.416486 0.213871-0.823761 0.304945-1.240247l74.881454-330.340637c1.596358-6.212492 2.257413-12.586666 2.00261-18.992563C960.892707 473.366098 953.948551 446.331371 939.358251 423.424662z"
                :fill="comment.action ? '#05adeb' : '#999999'"
                p-id="5364"
              ></path>
              <path
                d="M450.027553 518.650467c-17.253966 0-31.233352 13.979386-31.233352 31.233352l0 30.470989c0 17.253966 13.979386 31.233352 31.233352 31.233352 17.253966 0 31.233352-13.979386 31.233352-31.233352l0-30.470989C481.260905 532.629853 467.281519 518.650467 450.027553 518.650467z"
                :fill="comment.action ? '#05adeb' : '#999999'"
                p-id="5365"
              ></path>
              <path
                d="M693.805696 518.650467c-17.253966 0-31.233352 13.979386-31.233352 31.233352l0 30.470989c0 17.253966 13.979386 31.233352 31.233352 31.233352 17.253966 0 31.233352-13.979386 31.233352-31.233352l0-30.470989C725.039048 532.629853 711.058638 518.650467 693.805696 518.650467z"
                :fill="comment.action ? '#05adeb' : '#999999'"
                p-id="5366"
              ></path>
              <path
                d="M648.940882 660.09492c-14.304797-9.393951-33.592073-5.398964-43.159986 8.763594-0.132006 0.193405-13.614066 19.754926-34.171264 19.754926-19.98824 0-32.423457-18.09717-33.266661-19.368116-9.17087-14.427594-28.254507-18.809391-42.834574-9.770528-14.650675 9.109472-19.155269 28.366048-10.055007 43.016723 11.214413 18.047028 41.96988 48.588625 86.156242 48.588625 43.962258 0 75.104535-30.318516 86.572728-48.222281C667.404396 688.461991 663.216004 669.500127 648.940882 660.09492z"
                :fill="comment.action ? '#05adeb' : '#999999'"
                p-id="5367"
              ></path>
            </svg>
          </span>
          <span>{{ comment.like }}</span>
          <span @click="toggleReplyBox(comment.id, null, comment.username)">
            回复
          </span>
        </div>
        <!-- 回复列表，带折叠/展开 -->
        <div v-if="comment?.replies?.length" class="reply-section">
          <div
            v-for="(reply, index) in displayedReplies(comment)"
            :key="reply.id"
            class="reply-item"
          >
            <div class="reply-comment-left">
              <el-avatar :src="reply.avatar" size="small"><span style="font-size: 12px;">游客</span></el-avatar>
            </div>
            <div class="reply-comment-right">
              <div class="reply-content">
                <span class="comment-username">{{ reply.username }}</span>
                <p>{{ reply.content }}</p>
                <el-image
                  v-if="reply.commentPic"
                  style="width: 190px; height: 135px"
                  :src="reply.commentPic"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="[reply.commentPic]"
                  :initial-index="0"
                  fit="cover"
                />
              </div>
              <div class="comment-footer">
                <span>{{ comment.createDate }}</span>
                <span @click="like(reply)">
                  <svg
                    t="1728311247743"
                    class="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="5363"
                    width="16"
                    height="16"
                  >
                    <path
                      d="M939.358251 423.424662c-23.01825-37.252439-62.924121-60.779272-107.019409-63.209624-2.755764-0.38681-5.510504-0.579191-8.347109-0.579191l-152.202471-0.121773c6.649444-28.975938 10.015098-58.653865 10.015098-88.657202 0-28.223808-3.213181-57.139372-9.556657-85.952604-0.447185-2.043542-1.098008-4.006244-1.932002-5.866614-15.820314-57.302077-67.37755-96.841605-127.282918-96.841605-72.827679 0-132.081201 59.254545-132.081201 132.081201 0 3.334955 0.132006 6.66991 0.406253 10.015098-2.196015 57.211003-32.108279 109.947088-80.269162 141.363611-14.447037 9.42465-18.524912 28.773324-9.099239 43.220361 9.414417 14.437827 28.752858 18.535145 43.220361 9.099239 65.811892-42.925648 106.429984-115.325585 108.656699-193.684234 0.030699-1.332345-0.010233-2.663666-0.14224-3.996011-0.203638-2.012843-0.304945-4.016477-0.304945-6.019087 0-38.381146 31.233352-69.614497 69.614497-69.614497 32.57593 0 60.474326 22.204721 67.824735 53.997821 0.356111 1.534959 0.823761 3.019777 1.402953 4.453429 4.696975 22.814612 7.076162 45.579081 7.076162 67.743894 0 37.485753-6.222725 74.352405-18.494213 109.592001-3.324722 9.546424-1.819438 20.111037 4.02671 28.345582 5.856381 8.245801 15.332197 13.146415 25.448602 13.156648l193.226816 0.101307c1.423419 0.264013 2.857071 0.426719 4.300956 0.477884 24.116257 0.9967 45.935192 13.614066 58.603723 34.090423 7.838525 12.31242 11.438517 26.800389 10.431583 41.939181-0.080841 0.945535-0.121773 1.911536-0.11154 2.877537 0 0.854461 0.040932 1.697665 0.11154 2.53166 0.010233 0.335644-0.030699 0.661056-0.11154 0.976234-0.101307 0.376577-0.193405 0.772596-0.284479 1.159406l-74.972529 330.391802c-0.914836 1.281179-1.738597 2.6432-2.449795 4.046153-5.937223 11.762905-14.660908 21.48329-25.346271 28.172643-10.746762 6.812149-23.059182 10.614755-35.757388 11.06194-0.854461-0.061398-513.766226-0.224104-513.766226-0.224104-0.467651-0.020466-0.935302-0.030699-1.402953-0.030699 0 0-111.01542 0.172939-112.718201 0.457418-1.932002 0-3.446495-1.50426-3.446495-3.415796l0.299829-416.334173c0-1.901303 1.545192-3.446495 3.01466-3.456728l1.245364 0.121773c1.174756 0.132006 2.653433 0.284479 3.52836 0.193405l83.82822-0.222057 0 339.367221c0 17.253966 13.979386 31.233352 31.233352 31.233352s31.233352-13.979386 31.233352-31.233352L281.009092 435.350273c0-1.778506 0-8.631588 0-10.411117 0-17.253966-13.979386-30.928407-31.233352-30.928407-1.50426 0-117.547183 0.304945-119.402437 0.304945-36.34272 0-65.913199 29.566386-65.913199 65.893756l-0.299829 416.334173c0 36.337603 29.571503 65.902966 65.913199 65.902966 2.541893 0 111.406323-0.457418 111.406323-0.457418 0.457418 0.020466 0.925069 0.030699 1.382487 0.030699 0 0 511.458671 0.274246 512.505513 0.274246 25.469068 0 50.296523-7.197936 71.647807-20.73116 19.612687-12.281721 35.777855-29.881564 46.839795-50.967812 3.660366-5.622044 6.435573-11.875468 8.256034-18.615986 0.11154-0.416486 0.213871-0.823761 0.304945-1.240247l74.881454-330.340637c1.596358-6.212492 2.257413-12.586666 2.00261-18.992563C960.892707 473.366098 953.948551 446.331371 939.358251 423.424662z"
                      :fill="reply.action ? '#05adeb' : '#999999'"
                      p-id="5364"
                    ></path>
                    <path
                      d="M450.027553 518.650467c-17.253966 0-31.233352 13.979386-31.233352 31.233352l0 30.470989c0 17.253966 13.979386 31.233352 31.233352 31.233352 17.253966 0 31.233352-13.979386 31.233352-31.233352l0-30.470989C481.260905 532.629853 467.281519 518.650467 450.027553 518.650467z"
                      :fill="reply.action ? '#05adeb' : '#999999'"
                      p-id="5365"
                    ></path>
                    <path
                      d="M693.805696 518.650467c-17.253966 0-31.233352 13.979386-31.233352 31.233352l0 30.470989c0 17.253966 13.979386 31.233352 31.233352 31.233352 17.253966 0 31.233352-13.979386 31.233352-31.233352l0-30.470989C725.039048 532.629853 711.058638 518.650467 693.805696 518.650467z"
                      :fill="reply.action ? '#05adeb' : '#999999'"
                      p-id="5366"
                    ></path>
                    <path
                      d="M648.940882 660.09492c-14.304797-9.393951-33.592073-5.398964-43.159986 8.763594-0.132006 0.193405-13.614066 19.754926-34.171264 19.754926-19.98824 0-32.423457-18.09717-33.266661-19.368116-9.17087-14.427594-28.254507-18.809391-42.834574-9.770528-14.650675 9.109472-19.155269 28.366048-10.055007 43.016723 11.214413 18.047028 41.96988 48.588625 86.156242 48.588625 43.962258 0 75.104535-30.318516 86.572728-48.222281C667.404396 688.461991 663.216004 669.500127 648.940882 660.09492z"
                      :fill="reply.action ? '#05adeb' : '#999999'"
                      p-id="5367"
                    ></path>
                  </svg>
                </span>
                <span style="margin-left: 10px">{{ reply.like }}</span>
                <span
                  @click="
                    toggleReplyBox(reply.id, reply.parentId, reply.username)
                  "
                >
                  回复
                </span>
              </div>
            </div>
          </div>
          <span
            v-if="!comment.showAllReplies && comment.replies.length > 1"
            type="text"
            @click="toggleReplies(comment.id)"
          >
            展开 {{ comment.replies.length }} 条回复
          </span>
          <span
            v-if="comment.showAllReplies && comment.replies.length > 1"
            type="text"
            @click="toggleReplies(comment.id)"
          >
            收起回复
          </span>
        </div>
        <!-- 回复输入框 -->
        <div>
          <CommentInput
            v-if="replyParentId === comment.id"
            :parent="false"
            v-model:input-text="replyInputText"
            @update:inputText="updateInputText"
            @publish="publishComment"
          ></CommentInput>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineEmits, ref, watch } from "vue";
import { ElAvatar, ElNotification } from "element-plus";
import { user } from "@/store";
import CommentInput from "./CommentInput.vue";
import { createComment } from "@/api/comment";
import { uploadImageToOss } from "@/utils/tools";
import { likeSomething, unlikeSomething } from "@/api/like";
const _Type = 3;
// const userStore = user();
const { getUserInfo } = user();
const userAvatar = getUserInfo?.headPic || "";
const props = defineProps({
  createId: {
    type: Number,
    default: null,
  },
  type: {
    type: Number,
    default: 0,
  },
  comments: {
    type: Array,
    default: [],
  },
  commentTotal: {
    type: Number,
    defatult: 0,
  },
});
const replyParentId = ref<number|null>(null); // 回复的父Id
const showReplyId = ref<number|null>(null); //回复对象的id
const replyMember = ref<string>(""); //回复对象的username
const emit = defineEmits(["refresh-comment", "order-change"]);

interface Comment {
  id: number;
  username: string;
  userId: number;
  // blogId: number;
  avatar: string;
  content: string;
  createDate: string;
  like: number;
  commentPic: string;
  parentId: number;
  type: number; //类型 1文章 2说说 3评论 4图片 。。。
  reply: number; //是否为回复
  showReply: boolean; //是否显示回复框
  replies: Comment[]; //回复
  showAllReplies?: boolean; //是否收起回复
  action: 0 | 1;
}
const orderBy = ref("hot");
const inputText = ref("");
const replyInputText = ref("");
const changeOrder = (type: "hot" | "new") => {
  orderBy.value = type;
  emit("refresh-comment", {
    createId: props.createId,
    orderType: orderBy.value,
  });
};
// const toggleExpand = () => {
//   isExpand.value = !isExpand.value;
// };

const comments = ref<Comment[]>([]);

/**
 * @发表评论
 * @param val.parent val.parent 是否为主评论（非回复的评论） @type: boolen
 */
const publishComment = async (val: any) => {
  // if (!userStore?.getUserInfo?.id) {
  //   userStore.setShowLogin(true);
  //   return;
  // }
  try {
    // isReplyParent 是否为主评论
    const isReplyParent: boolean = comments.value.some(
      (i: Comment) => i.id === showReplyId.value
    );
    // 发表评论或回复评论是否为空
    if (
      (val.parent && !inputText.value) ||
      (!val.parent && !replyInputText.value)
    ) {
      return ElNotification.error({
        title: "Failed",
        message: "请输入评论内容",
        offset: 100,
      });
    }

    // 回复谁
    let resPic: any = "";
    if (val?.data?.[0]) {
      resPic = await uploadImageToOss(val.data[0], 5);
    }

    interface PublishData {
      commentPic: string;
      avatar: string;
      createId: number;
      content: string;
      parentId?: number|null;
      memberId?: number|null;
      reply?: boolean;
      type: number;
      userId?: number,
      username?: string
    }
    let data: PublishData = {
      type: props.type,
      commentPic: resPic,
      avatar: userAvatar,
      createId: props.createId,
      content: val.parent ? inputText.value : replyInputText.value,
      userId: getUserInfo?.id || null,
      username: getUserInfo?.username || null
    };

    // 非评论且是回复主评论
    data.parentId = isReplyParent && val.parent ? null : replyParentId.value;
    if (!val.parent && !isReplyParent) {
      data.reply = true;
      data.memberId = showReplyId.value;
      data.content = `回复@${replyMember.value}:` + " " + data.content;
    }
    const res:any = await createComment(data);
    if (res?.status == 200 || res?.status == 201) {
      ElNotification.success({
        title: "Success",
        message: "发送评论成功",
        duration: 500,
        offset: 100,
      });
      emit("refresh-comment", {
        createId: props.createId,
        orderType: orderBy.value,
      });
    } else {
      ElNotification.error({
        title: "Failed",
        message: res?.message || "发送评论失败",
        offset: 100,
      });
    }
  } catch (error:any) {
    console.log(error, "报错啦");
    ElNotification.error({
      title: "Error",
      message: error.message,
      offset: 100,
    });
  }
};
const like = async (comment: Comment) => {
  /**
   * @param userId 点赞的用户id
   * @param id  点赞id
   * @param type 点赞类型
   */
  try {
    if (comment.action) {
      const res = await unlikeSomething({
        createId: comment.id,
        type: _Type,
      });
      if (res.status === 200 || res.status === 201) {
        comment.like -= 1;
        const action = !comment.action;
        comment.action = action ? 1 : 0;
      } else {
        ElNotification.error({
          title: "Failed",
          duration: 1000,
          message: "点赞失败",
        });
      }
    } else {
      const res = await likeSomething({
        createId: comment.id,
        authorId: comment.userId,
        userId: getUserInfo.id,
        type: _Type,
      });
      if (res.status === 200 || res.status === 201) {
        comment.like += 1;
        const action = !comment.action;
        comment.action = action ? 1 : 0;
      } else {
        ElNotification.error({
          title: "Failed",
          duration: 1000,
          message: "取消点赞失败",
        });
      }
    }
  } catch (error:any) {
    ElNotification.error({
      title: "Error",
      message: error?.message || "点赞失败",
      offset: 100,
    });
  }
};

// 回复
const toggleReplyBox = (id: number, parentId: number|null, name: string) => {
  replyMember.value = name;
  if (showReplyId.value === id && replyParentId.value !== 0) {
    replyParentId.value = 0;
  } else {
    replyParentId.value = parentId ? parentId : id;
  }
  showReplyId.value = id;
};

const updateInputText = (val: { text: string; parent: boolean }) => {
  if (val.parent) {
    inputText.value = val.text;
  } else {
    replyInputText.value = val.text;
  }
};
const toggleReplies = (id: number) => {
  const comment = comments.value.find((c) => c.id === id);
  if (comment) comment.showAllReplies = !comment.showAllReplies;
};

const displayedReplies = (comment: Comment) => {
  return comment.showAllReplies ? comment.replies : comment.replies.slice(0, 1);
};

watch(
  () => props.comments,
  (newValue: any) => {
    const comment = newValue.map((item: any) => {
      if (item?.replies?.length) {
        item.replies.map((repily: any) => {
          repily.showReply = false;
          return repily;
        });
      }
      item.showReply = false;
      item.showAllReplies = true;
      return item;
    });
    comments.value = comment;
  },
  {
    immediate: true,
    deep: true,
  }
);
</script>

<style lang="scss" scoped>
.comment-section {
  margin: 20px 10px 10px 0;
  .comment-header {
    @include flex($flex-start);
    .total-value {
      font-size: 18px;
    }
    div {
      margin-left: 2rem;
      span {
        font-size: 1rem;
        cursor: pointer;
      }
      .active-hot-new {
        color: #4f7cef;
      }
    }
  }
  .input-comment {
    display: flex;
    justify-content: flex-start;
    margin-top: 1rem;
    .el-avatar {
      flex: 0 0 auto;
    }
    div {
      flex: 1;
      height: auto;
      margin-left: 1rem;
    }
  }
}
.comment-card {
  display: flex;
  margin-bottom: 15px;
  margin-top: 20px;
  .comment-left {
    width: 32px;
    margin-right: 12px;
  }
  .comment-right {
    flex: 1;
    .comment-body {
      margin-top: 6px;
      font-size: 1em;
      .comment-username {
        color: #fb7289;
        font-size: 14px;
        font-weight: bold;
      }
      p {
        word-wrap: break-word;
      }
    }
    .comment-footer {
      display: flex;
      align-items: center;
      margin-top: 10px;
      span {
        font-size: 13px;
        color: gray;
        cursor: pointer;
      }
    }
    .reply-section {
      margin-top: 10px;
      .reply-item {
        margin-bottom: 10px;
        display: flex;
        .reply-comment-left {
          width: 32px;
          // margin-right: 12px;
        }
        .reply-comment-right {
          flex: 1;
          .reply-content {
            font-size: 0.9em;
          }
          .comment-username {
            font-size: 13px;
            color: #da4d8f;
            font-weight: bold;
          }
          .comment-footer {
            display: flex;
            align-items: center;
            margin-top: 6px;
            font-size: 13px;
            color: gray;
            span {
              cursor: pointer;
            }
          }
        }
      }
    }
  }
}

.comment-time {
  margin-left: auto;
  color: #999;
  font-size: 0.9em;
}

.reply-time {
  margin-left: auto;
  color: #999;
  font-size: 0.8em;
}
// mobile
@media screen and (max-width: 768px) {
  .comment-section {
    margin: 0;
  }
  .comment-footer {
    justify-content: space-between;
  }
}
// pc
@media screen and (min-width: 768px) {
  .comment-section {
    margin: 0;
  }
  .comment-footer {
    justify-content: flex-start;
    span {
      margin-right: 40px;
    }
  }
}
</style>
